/**
 * Created by ztt on 2017/11/17.
 */
var express = require('express');
var app = express();
var fs = require("fs");

/**
 * todo:跨域处理
 */
app.all('*', function(req, res, next) {
    res.header("Access-Control-Allow-Origin", "*");
    res.header("Access-Control-Allow-Headers", "X-Requested-With");
    res.header("Access-Control-Allow-Methods","PUT,POST,GET,DELETE,OPTIONS");
    res.header("X-Powered-By",' 3.2.1')
    res.header("Content-Type", "application/json;charset=utf-8");
    next();
});

app.get('/user/list', function (req, res) {
    res.header("Access-Control-Allow-Origin", "*");
    res.header("Access-Control-Allow-Headers", "X-Requested-With");
    res.header("Access-Control-Allow-Methods","PUT,POST,GET,DELETE,OPTIONS");
    res.header("X-Powered-By",' 3.2.1')
    res.header("Content-Type", "application/json;charset=utf-8");
    fs.readFile( __dirname + "/" + "users.json", 'utf8', function (err, data) {
        console.log( data );
        res.end( data );
    });
});
app.get('/user/:id',function (req,res) {
    res.header("Access-Control-Allow-Origin", "*");
    res.header("Access-Control-Allow-Headers", "X-Requested-With");
    res.header("Access-Control-Allow-Methods","PUT,POST,GET,DELETE,OPTIONS");
    res.header("X-Powered-By",' 3.2.1')
    res.header("Content-Type", "application/json;charset=utf-8");
   fs.readFile(__dirname+"/"+"users.json",'utf-8',function (err,data) {
       data=JSON.parse(data);
       var user=data["user"+req.params.id];
       if(user){
           res.send(JSON.stringify(user));
       }else{
           res.send('用户不存在!')
       }
   })
});
//添加的新用户数据
var user = {
    "user4" : {
        "name" : "mohit",
        "password" : "password4",
        "profession" : "teacher",
        "id": 4
    }
};
app.post('/user',function (req,res) {
    console.log('Hello Post');
    fs.readFile( __dirname + "/" + "users.json", 'utf8', function (err, data) {
        data = JSON.parse( data );
        data["user4"] = user["user4"];
        console.log( data );
        res.end( JSON.stringify(data));
    });
});
app.delete('/user/:id',function (req,res) {
    res.writeHead(200,{"Content-Type":"text/plain;charset=utf-8"});
    res.end('删除成功：'+req.params.id);
});
app.put('/user/:id',function (req,res) {
    res.writeHead(200,{"Content-Type":"text/plain;charset=utf-8"});
    res.end('更新成功：'+req.params.id);
});

//浏览器通过这种形式的url访问localhost/userlist?id=xxx&name=yyy，这种方式可以通过req.query.id获取参数的值
app.get('/organization/unique/', function(req, res, next) {
    let parentId=req.query.parentId;
    let name=req.query.name;
    console.log(`${parentId}=>${name}`);
    let result={"result":Math.random()>0.5,"message":"编码已存在！"};
    console.log(`${parentId}=>${name}`,result);
    res.send(result);
});

app.get('/user/unique/:id',function (req,res) {
    res.header("Access-Control-Allow-Origin", "*");
    res.header("Access-Control-Allow-Headers", "X-Requested-With");
    res.header("Access-Control-Allow-Methods","PUT,POST,GET,DELETE,OPTIONS");
    res.header("X-Powered-By",' 3.2.1')
    res.header("Content-Type", "application/json;charset=utf-8");
    fs.readFile(__dirname+"/"+"users.json",'utf-8',function (err,data) {
        data=JSON.parse(data);
        var user=data["user"+req.params.id];
        if(user){
            res.send(true);
        }else{
            res.send(false)
        }
    })
});


var https = require('https');
app.get("/csdn",function (req,res) {
    https.get('https://www.baidu.com', function(res){
        console.log('status code: ' + res.statusCode);
        console.log('headers: ' + res.headers);

        res.on('data', function(data){
            process.stdout.write(data);
        });
    }).on('error', function(err){
        console.error(err);
    });
});

var server = app.listen(3000, function () {
    var host = server.address().address
    var port = server.address().port
    console.log("应用实例，访问地址为 http://%s:%s", host, port)
});
